package com.jialiang.common.exception;

import com.google.common.collect.Iterables;
import com.jialiang.common.constants.CodeEnum;
import com.jialiang.common.model.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public abstract class BaseGlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(BaseGlobalExceptionHandler.class);

    public BaseGlobalExceptionHandler() {
        log.info("创建全局异常处理器对象：BaseGlobalExceptionHandler");
    }

    @ExceptionHandler
    public JsonObject<?> handleServiceException(BusinessException e) {
        log.debug("全局异常处理器开始处理ServiceException", e);
        return JsonObject.fail(e);
    }

    @ExceptionHandler
    public JsonObject<?> handleBindException(BindException e) {
        log.debug("全局异常处理器开始处理BindException");
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("请求参数格式错误，");
        stringBuilder.append(e.getFieldError().getDefaultMessage());
        stringBuilder.append("！");
        String message = stringBuilder.toString();
        log.warn(message);
        return JsonObject.fail(CodeEnum.ERROR_BAD_REQUEST, message);
    }

    @ExceptionHandler(SystemException.class)
    public JsonObject<?> handleSystemException(SystemException e){
        log.error("系统异常",e);
        return JsonObject.fail(CodeEnum.SystemError);
    }

    @ExceptionHandler(ValidationException.class)
    public JsonObject<?> handleValidateException(ValidationException validationException){
        if(Iterables.size(validationException.getResult()) > 0){
            return JsonObject.fail(validationException.getResult().get(0).getMessage());
        }
        return JsonObject.fail(CodeEnum.ParamSetIllegal.getName());
    }

    @ExceptionHandler
    public JsonObject<?> handleThrowable(Exception e) {
        log.error("全局异常处理器开始处理Exception");
        log.error("异常跟踪信息如下：", e);
        String message = "服务器忙，请稍后再试！【看到这句时，你应该检查服务器端的控制台，并在全局异常处理器中添加处理异常的方法】";
        return JsonObject.fail(CodeEnum.ERROR_UNKNOWN, message);
    }
}
